<template>
  <BasicDrawer
    v-bind="$attrs"
    :okAuth="'management:inFireInfo:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <!-- 展示设备状态信息的容器 -->
    <div v-if="equipmentStatusList && Object.keys(equipmentStatusList).length > 0" class="equipment-status-container">
      <div v-for="(itemList, category) in equipmentStatusList" :key="category" class="equipment-category">
        <!-- <h4>{{ category }}</h4> -->
        <div v-for="item in itemList" :key="item.equipmentName" class="equipment-item">
          <img v-if="item.state === '异常'" src="/@/assets/icons/close.svg"  style="width: 40px;height:auto;" alt="">
          <img v-if="item.state === '正常'" src="/@/assets/icons/open.svg"  style="width: 40px;height:auto;" alt="">
          <span>{{ item.equipmentName }}</span>
          <div v-if="item.parameter" style="font-size: 15px;height: 20px;" >{{item.parameter}}</div>
          <div v-else style="height: 20px;"></div>
        </div>
      </div>
    </div>
    <div class="fireVeIm">
      <div class="fireVideo">
        <span>
          报警视频：
        </span>
        <video
          width="100%"
          height="100%"
          :src="videoSrc"
          controls
          autoplay
          muted
          @loadeddata="onVideoLoaded"
          @error="onVideoError"
          type="video/mp4"
        >
        </video>
      </div>

      <div class="fireImg">
        <span>
          火情结束照片：
        </span>
        <Image v-if="imageSrc" :src="imageSrc" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" style="width: 150px;height:auto;" alt="">
      </div>
    </div>
    <BasicForm @register="registerForm" />
    <UploadFile />
    <div class="map-timeline-container">
      <div class="timeline-and-map">
        <a-timeline class="timeline">
          <!-- 遍历 1 到 6 级 -->
          <a-timeline-item v-for="level in [1, 2, 3, 4, 5, 6]" :key="level">
            <p>第{{ level }}级灭火力量</p>
            <!-- 查找对应级别的数据 -->
            <p v-if="getLevelData(level)">
              {{ getLevelData(level).confirmed ? `${getLevelData(level).notifierName} 于 ${getLevelData(level).confirmTime} 确认收到火情` : `${getLevelData(level).notifierName}未确认` }}
            </p>
            <p v-else>未确认</p>
          </a-timeline-item>
        </a-timeline>
        <div class="map-container">
          <BaiduMap :showButtons="false" :bound="[{ lng:Longitude, lat:Latitude }]" class="baidu-map"/>
        </div>
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsManagementInFireInfoForm">
  import { ref, unref, computed, onMounted,watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { InFireInfo, inFireInfoSave, inFireInfoForm } from '/@/api/management/inFireInfo';
  import { BpmButton } from '/@/components/Bpm';
  import BaiduMap from '/@/components/BMap';
  import { TestData } from '/@/api/test/testData';
  import { EquipmentStatus } from '/@/api/management/equipmentStatus';
  import { InFireNotificationData } from '/@/api/management/inFireNotification';
  import { Image, Timeline } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n('management.inFireInfo');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InFireInfo>({} as InFireInfo);
  const loadingRef = ref(false);
  const imageSrc = ref('');
  const videoSrc = ref('');
  const videoFireSrc = ref('');
  const notifications = ref([]);
  const baiduMapRef = ref(null);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增') : t('详情'),
  }));
  const Longitude=ref('')
  const Latitude=ref('')

  const inFireId = ref('');
  const timelineData = ref([]);
  // 存储设备状态信息
  const equipmentStatusList = ref<any>({});

  // 计算属性，对时间轴数据按 linkageLevel 排序
  const sortedTimelineData = computed(() => {
    return timelineData.value.slice().sort((a, b) => {
      return parseInt(a.linkageLevel) - parseInt(b.linkageLevel);
    });
  });

  // 根据级别获取数据的方法
  const getLevelData = (level: number) => {  
    // console.log('sortedTimelineData.value',level,sortedTimelineData.value);  
    return sortedTimelineData.value.find(item => parseInt(item.linkageLevel) === level);
  };

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('火情发起人'),
      field: 'fireInitiatorUser',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('所属主体'),
      field: 'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('火情名称'),
      field: 'fireName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('所属建筑'),
      field: 'buildName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('所属区域'),
      field: 'regionIname',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('详细地址'),
      field: 'location',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('火情确认时间'),
      field: 'fireConfirmTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true,
      },
    },
    {
      label: t('火情状态'),
      field: 'fireExecutionStatus',
      component: 'Input',
      componentProps: {
        maxlength: 10,
        disabled: true,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await inFireInfoForm(data);
    inFireId.value = res.inFireInfo.tid;
    record.value = (res.inFireInfo || {}) as InFireInfo;
    record.value.__t = new Date().getTime();
    imageSrc.value = record.value.confirmFireFile || '';
    videoSrc.value = record.value.fireVideo || '';
    Longitude.value=res.inFireInfo.longitude
    Latitude.value=res.inFireInfo.latitude
   
    setFieldsValue(record.value);

    // 调用 InFireNotificationData 接口获取时间轴数据
    try {
      const params = { mainId: inFireId.value };
      const timelineRes = await InFireNotificationData(params);
      timelineData.value = timelineRes.list || [];
    } catch (error) {
      console.error('获取时间轴数据失败:', error);
    }

    // 调用 EquipmentStatus 接口获取设备状态数据，并传入 inFireId.value
    try {
      const data = {
        FireInfoId: inFireId.value
      };
      const res = await EquipmentStatus({ FireInfoId: inFireId.value}, data);
      equipmentStatusList.value = res;
      console.log(equipmentStatusList.value);
    } catch (error) {
      console.error('获取设备状态数据失败:', error);
    }

    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      const res = await inFireInfoSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }

  const onVideoLoaded = () => {
    const video = document.querySelector('video');
    if (video && video.readyState >= video.HAVE_ENOUGH_DATA) {
      video.play().catch((error) => {
        console.error('视频播放错误:', error);
      });
    }
    console.log('视频加载完成');
  };

  const onVideoError = (event) => {
    const video = event.target;
    console.error('视频加载失败:', video.error);
    console.error('视频网络状态:', video.networkState);
    console.error('视频就绪状态:', video.readyState);
  };
  onMounted(() => {
    watch(() => baiduMapRef.value?.mapLoaded, (isLoaded) => {
        if (isLoaded) {
            // 地图加载完成后执行相关操作
        }
    });
});
</script>
<style scoped lang="less">
.fireVeIm {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
.fireVideo {
  width: 20%;
  height: 200px;
}
.map-timeline-container {
  display: flex;
}
.timeline-and-map {
  display: flex;
  width: 100%;
}
.timeline {
  width: 50%;
  padding: 10px;
}
.map-container {
  width: 50%;
}
.equipment-status-container {
  margin-bottom: 10px;
  height: 120px;
  width: 100%;
  border-bottom: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: space-around;
  font-size: 18px;
}
.equipment-category {
  margin-bottom: 10px;
  // border: 1px solid #ccc;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; 
}
.equipment-item {
  margin-bottom: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>